package com.toutiao.time

import net.liftweb.json.{JsonAST,Extraction,Printer,parse}
import net.liftweb.json.JsonDSL._

//import com.toutiao.issue.Event
import com.toutiao.issue.SimpleDate

import org.msgpack.ScalaMessagePack

	case class RawEvent(
			i:String,
			c:String,u:String,
			v:Map[String,Double],
			t:String,
			m:List[String]
	    )

object Converter {
  
  implicit val _ = net.liftweb.json.DefaultFormats
  
  def convertEvent(e:Event) = {
    val vs = e.vs
    val ct = SimpleDate.format(e.ct)
    val ut = SimpleDate.format(e.ut)
    val ms = e.ms.toList
    val name = e.nm
    val title = e.title
    
    val z = ("i"->name)~("c"->ct)~("u"->ut)~
    		("v"->vs)~("m"->ms)~("t"->title)
    		
    Printer.compact(JsonAST.render(z))
  }
  
  def convertLine(e:Event) = {
    val vs = e.vs.map(vv => {
      (vv._1+":"+"%.6f".format(vv._2))
    }).mkString(" ")
    val ct = SimpleDate.format(e.ct)
    val ut = SimpleDate.format(e.ut)
    val ms = e.ms.mkString(" ")
    val name = e.nm
    val title = e.title
    
    val xs = Array(name,ct,ut,vs,title,ms)
    xs.mkString("\t")
  }
  
  def convertData(e:Event) = {
    val x = ScalaMessagePack.write(e)
    x
  }
  
  
  def parseEvent(line:String) = {
    val s = parse(line).extract[RawEvent]
    
    val name = s.i
    val ct = SimpleDate.parse(s.c)
    val ut = SimpleDate.parse(s.u)
    val vs = s.v
    val title = s.t
    val ms = s.m.toArray
    
    //new Event(name,ms,vs,ct,ut,1.0)
    
    val e = new Event
    e.nm = name
    e.ct = ct
    e.ut = ut
    e.vs = vs
    e.s = 1.0
    e.title = title
    e.ms = ms
    
    e
  }
  
  def parseLine(line:String) = {
    val xs = line.split("\t")
    val name = xs(0)
    val ct = SimpleDate.parse(xs(1))
    val ut = SimpleDate.parse(xs(2))
    //val ut = ct
    val vs = xs(3).split(" ").map(vv => {
      val x = vv.split(":")
      val v = x(0)
      val s = x(1).toDouble
      (v,s)
    }).toMap
    val title = xs(4)
    val ms = xs(5).split(" ")
    //val ms = Array(name)
    
    //new Event(name,ms,vs,ct,ut,1.0)
    val e = new Event
    e.nm = name
    e.ct = ct
    e.ut = ut
    e.ms = ms
    e.vs = vs
    e.s = 1.0
    e.title = title
    e
  }
  
  def parseData(x:Array[Byte]) = {
    ScalaMessagePack.read[Event](x)
  }

}
